/**
 * Copyright (c) 2012 Nokia Corporation. 
 */

package com.nokia.example.tictactoe.connectivity;

import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;

/**
 * A client for datagram connections.
 */
public class UdpClient extends Connection {
	// Members
	protected DatagramConnection _udpConnection = null;
	protected Datagram _datagram = null;
	protected Integer _port = null;
	
	/**
	 * Constructor.
	 */
	public UdpClient() {
	}
	
	/**
	 * From Connection.
	 */
	public synchronized boolean open(String hostname, Integer port) {
		if (_running) {
			System.out.println("UdpClient::open(): Already open!");
			return false;
		}
		
		setState(CONNECTING);
		_port = port;

		new Thread() {
			public void run() {
				log("UDP client started");
				_running = true;
				
				try {
					// Open the connection and start listening for datagrams
					_udpConnection =
							(DatagramConnection)Connector.open("datagram://localhost:"
									+ _port.toString());
					setState(CONNECTED);
				} catch (IOException e) {	
					if (_running) {
						notifyFatalError("UDP client failed to open connection: "
								+ e.toString());
						close();
					}
				}
				
				while (_running) {
					// Nothing to do here but to keep the thread running
				}
				
				setState(DISCONNECTING);
				_datagram = null;
				
				try {
					if (_udpConnection != null) {
						_udpConnection.close();
					}
				} catch (IOException e) {}
				
				_udpConnection = null;
				setState(NOT_CONNECTED);
			}
		}.start();
		
		return true;
	}
	
	/**
	 * From Connection.
	 */
	public synchronized boolean send(byte[] message) {
		if (_udpConnection == null) {
			System.out.println("UdpClient::send(): No connection!");
			return false;
		}
		
		try {
			_datagram = _udpConnection.newDatagram(message, message.length);
			_udpConnection.send(_datagram);
			notifyMessageSent(message);
		}
		catch (IOException e) {
			notifyError("UDP client failed to send message: " + e.toString());
			return false;
		}
		
		return true;
	}
	
	/**
	 * From Connection.
	 */
	public synchronized void close() {
		System.out.println("UdpClient::close()");
		_running = false;
	}
}
